package top.lingkang.webssh.utils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author lingkang
 * @create by 2024/3/20 15:18
 */
public class CommonUtils {

    /**
     * 判断端口是否可用
     *
     * @param port 端口
     * @return 是否可用
     */
    public static boolean isPortAvailable(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            // 如果能够成功打开此端口，那么它就是可用的
            return true;
        } catch (Exception e) {
            // 发生异常则表示端口已被占用
            return false;
        }
    }

    public static boolean isLinux() {
        return System.getProperty("os.name").toLowerCase().contains("linux");
    }

    public static boolean isWindow() {
        return System.getProperty("os.name").toLowerCase().contains("win");
    }

    public static boolean isUbuntu() {
        return getOSName().equalsIgnoreCase("ubuntu");
    }

    public static boolean isCentOS() {
        return getOSName().toLowerCase().contains("centos");
    }

    private static String osName = null;

    private static String getOSName() {
        if (osName != null)
            return osName;
        if (isWindow()) {
            osName = "window";
            return osName;
        }
        try (BufferedReader br = new BufferedReader(new FileReader("/etc/os-release"))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.startsWith("NAME=")) {
                    osName = line.substring(line.indexOf("=") + 1).replaceAll("\"", "");
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return osName.trim();
    }
}
